//
//  MainViewController.m
//  CommuteWarriorUtility
//
//  Created by Rohit Mathews on 5/6/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MainViewController.h"
#include "TargetConditionals.h"
#include "DDFileReader.h"
#include "DDLog.h"
#include "DDFileLogger.h"
#include "DDASLLogger.h"
#include "DDTTYLogger.h"


//#define SOAP_SEND_COORDINATE_URL = "http://www.vmtinc.com/projects/webservice/soapServer.php"
//#define SOAP_NAMESPACE = "urn://www.vmtinc.com/projects/webservice"
//#define SEND_COORDINATE_METHOD_NAME = "sendCoordinates"
//#define SEND_FILE_METHOD_NAME = "sendTrip"
//#define CORRIDOR_CHECK_INTERVAL = 15
//#define LOW_SPEED_TIMEOUT = 300
//#define TEST_MODE

static int timeSinceCorridorIntervalCheck = 0;
static BOOL isInCorridor = YES;
static int timeSinceLowSpeed = 0;
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#ifdef	TEST_MODE
static float fTestCounter = 0.0;
#endif

// Constants
static int CORRIDOR_CHECK_INTERVAL = 15;
static int LOW_SPEED_TIMEOUT = 300;

NSString* const SOAP_SEND_COORDINATE_URL = @"http://www.vmtinc.com/projects/webservice/soapServer.php";
static const NSString* SOAP_NAMESPACE = @"urn://www.vmtinc.com/projects/webservice";
NSString*  const SEND_COORDINATE_METHOD_NAME = @"sendCoordinates";
static const NSString* SEND_FILE_METHOD_NAME = @"sendTrip";

// Preferences we are storing in NSUserDefaults
static NSString* PREF_LOGGING_ENABLED = @"loggingEnabled";
static NSString* PREF_TRIP_STARTED = @"tripStarted";
static NSString* OPERATE_ON_BATTERY = @"Operate_On_Battery";
static NSString* MIN_BATTERY_LVL = @"Minimum_Battery_Level";

@implementation MainViewController

@synthesize bkgndImage;
@synthesize startStopLogging;
@synthesize locationManager;
@synthesize logFilePath;
@synthesize applicationStatusLabel;

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller {
	[self dismissModalViewControllerAnimated:YES];
	[self updateApplicationStatusLabel];
}


- (IBAction)showInfo:(id)sender {    
	
	FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
	controller.delegate = self;
	
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:controller animated:YES];
	
	[controller release];
}

- (void)initializePreferenceValues{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	if([userDefaults objectForKey:OPERATE_ON_BATTERY] == nil){
		[userDefaults setBool:NO forKey:OPERATE_ON_BATTERY];
	}
	if([userDefaults objectForKey:MIN_BATTERY_LVL] == nil){
		[userDefaults setFloat:50.0 forKey:MIN_BATTERY_LVL];
	}	
}


-(void)toggleButtonText{
	if([startStopLogging.currentTitle isEqualToString:@"Start Logging"]){
		[startStopLogging setTitle:@"Stop Logging" forState:UIControlStateNormal];
	}
	else{
		[startStopLogging setTitle:@"Start Logging" forState:UIControlStateNormal];
	}
}

-(IBAction)startLoggingPushed:(id)sender{ 
	NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
	if([startStopLogging.currentTitle isEqualToString:@"Start Logging"]){
		[startStopLogging setTitle:@"Stop Logging" forState:UIControlStateNormal];
		[userPreferences setBool:YES forKey:PREF_LOGGING_ENABLED];
		// New trip has started. Check for when speed goes above 5 and then start recording.
		[userPreferences setBool:NO forKey:PREF_TRIP_STARTED];
		// Generate notification to inform user. Notification will also be an indication to user that app is running in the background.
		[self localNotificationToUser:YES];
		[locationManager startUpdatingLocation];
	}
	else{
		[startStopLogging setTitle:@"Start Logging" forState:UIControlStateNormal];
		[userPreferences setBool:NO forKey:PREF_LOGGING_ENABLED];
		// User has requested to stop recording. So, effectively trip has ended.
		[userPreferences setBool:NO forKey:PREF_TRIP_STARTED];
		// Remove badge
		[[UIApplication sharedApplication] cancelAllLocalNotifications];
		[locationManager stopUpdatingLocation];
	}
	[self updateApplicationStatusLabel];
}

-(void)updateCorridorStatusFromServerResponse:(NSString *)serverResponse{
	NSRange range = [serverResponse rangeOfString:@"</return></ns1:sendCoordinatesResponse>"];
	char corridorStatus = [serverResponse characterAtIndex:(range.location - 1)];
	if( corridorStatus == '1'){
		DDLogInfo(@"User is in corridor");
		isInCorridor = YES;
	}
	else{
		DDLogInfo(@"User is not in corridor");
		isInCorridor = NO;
	}
	DDLogInfo(@"Is in Corridor : %c", corridorStatus);
}

-(void)sendCoordinatesViaSoap:(NSString *)coordinateString toMethod:(const NSString *)methodName{
	NSMutableURLRequest *soapRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:SOAP_SEND_COORDINATE_URL]];
	[soapRequest setHTTPMethod:@"POST"];
	[soapRequest setValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[soapRequest setValue:@"nnn" forHTTPHeaderField:@"Content-Length"];
	
	/*NSString *httpBody = [NSString stringWithFormat:
	 @"<?xml version=\"1.0\"?>
	 <soap:Envelope
	 xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\"
	 soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">
	 
	 <soap:Body xmlns:m=\"%@\">
	 <m:%@>
	 <m:param1>%@</m:param1>
	 </m:%@>
	 </soap:Body>
	 
	 </soap:Envelope>",
	 SOAP_NAMESPACE, methodName, coordinateString, methodName];*/
	NSString *httpBody = [NSString stringWithFormat:@"<?xml version=\"1.0\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\"  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soap:Body xmlns:m=\"%@\"><m:%@><m:param1 xsi:type=\"xsd:string\">%@</m:param1></m:%@></soap:Body></soap:Envelope>",
						  SOAP_NAMESPACE, methodName, coordinateString, methodName];
	NSData *httpBodyAsData = [NSData dataWithBytes: [httpBody UTF8String] length: [httpBody length]];
	
	DDLogInfo(@"Http Body is %@", httpBody);
	
	[soapRequest setHTTPBody:httpBodyAsData];
	
	NSData *returnData = [NSURLConnection sendSynchronousRequest:soapRequest returningResponse:nil error:nil];
	NSString *serverResponse = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
	DDLogInfo(@"Server Response : %@", serverResponse);
	
	if([methodName isEqualToString:SEND_COORDINATE_METHOD_NAME]){
		[self updateCorridorStatusFromServerResponse:serverResponse];
	}
	
	//TODO: Release variables after testing.
	[serverResponse release];
}

-(NSString *)getCoordinateString:(CLLocation *)newLocation {
	double currentSpeed = TARGET_IPHONE_SIMULATOR ? 10 : newLocation.speed;
	// Testing speed
#ifdef TEST_MODE
	currentSpeed = 13.0 + fTestCounter;
#endif
	// First get the date in the format YYYY-MM-DD,HH:MM:SS
	NSDate *now = [NSDate date];
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"yyyy-MM-dd,hh:mm:ss"];
	NSString *dateString = [dateFormat stringFromDate:now];
	DDLogInfo(@"Obtained current date as %@", dateString);
	
	// Now add the latitude, longitude and speed
	NSString *latLongSpeed = [[NSString alloc] initWithFormat:@"%f, %f, %f, %f, -1, -1, -1, %d",
							  newLocation.coordinate.latitude, newLocation.coordinate.longitude,
							  newLocation.course, currentSpeed, newLocation.horizontalAccuracy];
	DDLogInfo(@"Current Speed = %f, 0", currentSpeed);
	DDLogInfo(@"Obtained latLongSpeed as %@", latLongSpeed);
	
	NSString *coordinateString = [[[NSString alloc] initWithFormat:@"%@,%@\n",
								   dateString, latLongSpeed] autorelease];
	
	[latLongSpeed release];
	[dateFormat release];
	
	return coordinateString;
}

-(void)sendFileToServer{
	DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:logFilePath];
	NSString *line = nil;
	int lineCount = 1;
	NSMutableString *fileContents = [[[NSMutableString alloc] init] autorelease];
	NSDate *today = [NSDate date];
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"yyyyMMdd.hhmmss"];
	NSString *dateString = [dateFormat stringFromDate:today];
	//str+=IMEI+"."+Integer.toString(time.year)+Integer.toString(time.month)+Integer.toString(time.monthDay)+"."+Integer.toString(time.hour)+Integer.toString(time.minute)+Integer.toString(time.second)+".csv\n";
	NSString *fileName = [[NSString alloc] initWithFormat:@"%@.%@.csv\n",
						  [[UIDevice currentDevice] uniqueIdentifier],
						  dateString];
	DDLogInfo(@"Now sending file : %@", fileName);
	[fileContents appendString:fileName];
	while ((line = [reader readLine])) {
		DDLogInfo(@"read line: %@", line);
		[fileContents appendString:line];
		if(lineCount % 120 == 0){
			[self sendCoordinatesViaSoap:fileContents toMethod:SEND_FILE_METHOD_NAME];
			// Reset the lineCount and fileContents
			lineCount = 0;
			[fileContents setString:@""];
		}
	}
	// Now send the remaining lines
	if([fileContents length] != 0){
		[self sendCoordinatesViaSoap:fileContents toMethod:SEND_FILE_METHOD_NAME];
	}
	// TODO: Delete the file after sending it to server??
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager removeItemAtPath:logFilePath error:nil];
	DDLogInfo(@"Deleted logFile for current trip");
	
	[dateFormat release];
	[fileName release];
	[reader release];
}

-(void)localNotificationToUser:(BOOL)shouldDeliverNow{
	UILocalNotification *localNotif = [[UILocalNotification alloc] init];
	if(localNotif == nil){
		DDLogInfo(@"Failed to initialize local Notification");
		return;
	}
	
	localNotif.alertBody = @"Commute Warrior has started recording location";
	localNotif.alertAction = @"Start";
	localNotif.soundName = UILocalNotificationDefaultSoundName;
	localNotif.applicationIconBadgeNumber = 1;
	
	if(shouldDeliverNow){
		[[UIApplication sharedApplication] presentLocalNotificationNow:localNotif];
	}
	else{
		NSDate *scheduleDateTime = [[NSDate alloc] initWithTimeIntervalSinceNow:30];
		localNotif.fireDate = scheduleDateTime;
		[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
	}
	
	[localNotif release];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation *) oldLocation{
	DDLogInfo(@"LocationManager didUpdateToLocation called");
	NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
	// Determine if device charging
	if(TARGET_IPHONE_SIMULATOR || ([userPreferences boolForKey:PREF_LOGGING_ENABLED] && [self areBatteryPreferencesMet])){	// TODO: Code to reflect actual battery state
		
		//If we were awoken from background on being called by SignificantLocationUpdate ask user to bring app to foreground to process data
		if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground){
			//	[self localNotificationToUser:YES];
		}
		
		double currentSpeed = newLocation.speed;		// Speed obtained is in meters/second
		// Get the next update after one second
		if(currentSpeed < 10){
			[locationManager setDistanceFilter:10];
		}
		else{
			[locationManager setDistanceFilter:currentSpeed];	// Distance filter is in meters
		}
		
		
		// Convert speed to miles/hour
		currentSpeed = currentSpeed * (18/5) * 0.62137;
		if(TARGET_IPHONE_SIMULATOR){
			currentSpeed = 10.0;
		}
		
#ifdef TEST_MODE
		if(currentSpeed <= 5){
			currentSpeed = 13 + fTestCounter;	// Added for testing purpose.
			++fTestCounter;
		}
#endif
		
		if(currentSpeed >= 5){
			
			// Reset time since low speed to zero
			timeSinceLowSpeed = 0;
			
			// If trip has started, save user state that has trip has been initiated.
			[userPreferences setBool:YES forKey:PREF_TRIP_STARTED];
			
			DDLogInfo(@"Speed currently greater than 5");
			
#ifdef TEST_MODE
			DDLogInfo(@"fTestCounter %f", fTestCounter);
			if(fTestCounter == 6){
				DDLogInfo(@"Sending file to server now");
				[self sendFileToServer];
			}
#endif
		}
		else{
			if([userPreferences boolForKey:PREF_TRIP_STARTED]){
				// We are currently in a trip. Continue recording data.
				DDLogInfo(@"Current speed less than 5 mph.");
				++timeSinceLowSpeed;
				// If we were stationary for more 5 minutes, trip has ended. Mark this and send this information to the server.
				if(timeSinceLowSpeed > LOW_SPEED_TIMEOUT){
					timeSinceLowSpeed = 0;	// Reset it
					[userPreferences setBool:NO forKey:PREF_TRIP_STARTED];
					[locationManager stopUpdatingLocation];
					[locationManager startMonitoringSignificantLocationChanges];
					[self sendFileToServer];
				}				
			}
		}
		BOOL testMode = NO;
#ifdef TEST_MODE
		testMode = YES;
#endif
		if(testMode || [userPreferences boolForKey:PREF_TRIP_STARTED]){
			
			NSString *logContent = [[self getCoordinateString:newLocation] retain];
			//[logContent writeToFile:logFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
			NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:logFilePath];
			if(fileHandle == nil){
				DDLogInfo(@"File Handle for updating at path is nil");
			}
			[fileHandle seekToEndOfFile];
			NSData *data = [logContent dataUsingEncoding:NSUTF8StringEncoding];
			[fileHandle writeData:data];
			[fileHandle closeFile];
			[logContent release];
			
			//For first entry into function isInCorridorInterval is YES, so it will enter this loop to check corridor status
			if(isInCorridor){
				// If we are in the corridor log data to server
				DDLogInfo(@"Logging data to Server since we are in corridor");
				[self sendCoordinatesViaSoap:logContent toMethod:SEND_COORDINATE_METHOD_NAME];
			}
			else{
				// If we are not in corridor, check if 15 seconds have passed that we have not been in corridor. Then update.
				if(timeSinceCorridorIntervalCheck%CORRIDOR_CHECK_INTERVAL == 0){
					[self sendCoordinatesViaSoap:logContent toMethod:SEND_COORDINATE_METHOD_NAME];
				}
				++timeSinceCorridorIntervalCheck;
			}		
		}
	}
}

-(BOOL)isDeviceCharging{
	DDLogInfo(@"Determining device battery status");
	UIDevice *thisDevice = [UIDevice currentDevice];
	thisDevice.batteryMonitoringEnabled = YES;
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStateChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:thisDevice];
	if(thisDevice.batteryState == UIDeviceBatteryStateCharging || thisDevice.batteryState == UIDeviceBatteryStateFull){
		DDLogInfo(@"Device is charging");
		return YES;
	}
	else{
		DDLogInfo(@"Device is not charging");
		return NO;
	}
}

-(BOOL) areBatteryPreferencesMet{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	if([userDefaults boolForKey:OPERATE_ON_BATTERY] == NO){
		return [self isDeviceCharging];
	}
	else{
		UIDevice *thisDevice = [UIDevice currentDevice];
		DDLogInfo(@"Current Battery Level %f", thisDevice.batteryLevel);
        DDLogInfo(@"Minimum Battery Level %f", [userDefaults floatForKey:MIN_BATTERY_LVL]/100);
		return ([userDefaults floatForKey:MIN_BATTERY_LVL]/100 < thisDevice.batteryLevel);
	}
}

-(void)batteryStateChanged:(NSNotification *)notification {
	//	UIDevice *device = [UIDevice currentDevice];
	//TODO: Determine current state and act accordingly.
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
	if(error.code == kCLErrorDenied){
		//Turn off the location manager updates
		[manager stopUpdatingLocation];
		[locationManager release];
		locationManager = nil;
	}
}

/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	// Setup the UI
	NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
	// By default it starts with Logging Disabled
	if([preferences objectForKey:PREF_LOGGING_ENABLED] != nil){
		NSString *loggerButtonTitle = [preferences boolForKey:PREF_LOGGING_ENABLED] == YES ?
		@"Stop Logging":@"Start Logging";
		[startStopLogging setTitle:loggerButtonTitle forState:UIControlStateNormal];
	}
	else{
		[preferences setBool:NO forKey:PREF_LOGGING_ENABLED];
	}
	[self initializePreferenceValues];
	[self updateApplicationStatusLabel];
	// End UI setup
	
	
	// Setup battery monitoring
	UIDevice *thisDevice = [UIDevice currentDevice];
	thisDevice.batteryMonitoringEnabled = YES;
	DDLogInfo(@"Device UUID number is %@", [thisDevice uniqueIdentifier]);
	
	//	DDLogInfo(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
	//	DDLogInfo(@"Phone number is %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"	"]);
	
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStateChanged:) 
												 name:@"UIDeviceBatteryStateDidChangeNotification"
											   object:thisDevice];
	
	// Subscribe to location Manager
	locationManager = [[CLLocationManager alloc] init];
	locationManager.delegate = self;
	locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	
	// Get the log file to which we will be appending data.
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *docDirectory = [paths objectAtIndex:0];
	logFilePath = [docDirectory stringByAppendingPathComponent:@"CommuteWarrior.txt"];
	[logFilePath retain];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if(![fileManager fileExistsAtPath:logFilePath]){
		BOOL created = [fileManager createFileAtPath:logFilePath contents:nil attributes:nil];
		if(created){
			DDLogInfo(@"Successfully created file at path");
		}
		else{
			DDLogInfo(@"Did not create file at path");
		}
	}	
	DDLogInfo(@"logFilePath is %@", logFilePath);
	
	// If we are in simulator, updateLocation will not be called. Call it with dummy values.
	if(TARGET_IPHONE_SIMULATOR){
		CLLocation *dummyLocation = [[CLLocation alloc] initWithLatitude:33.776160 longitude:-84.39887];
		//CLLocation *dummyLocation = [[CLLocation alloc] initWithCoordinate:dummyCoordinates altitude:2.0 horizontalAccuracy:2.0 verticalAccuracy:2.0 timestamp:now];
		[self locationManager:locationManager didUpdateToLocation:dummyLocation fromLocation:nil];
		[self localNotificationToUser:NO];
		[dummyLocation release];
	}
	
	[super viewDidLoad];
}

-(void)applicationWillResignActive:(UIApplication *)application{
	DDLogInfo(@"Application will resign active called");
	//[locationManager startMonitoringSignificantLocationChanges];
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
	DDLogInfo(@"Application did Enter Background called");
}

-(void)applicationWillEnterForeground:(UIApplication *)application{
	DDLogInfo(@"Application now entering foreground");
	//[locationManager stopMonitoringSignificantLocationChanges];
	//[locationManager startUpdatingLocation];
}

-(void)applicationWillTerminate:(UIApplication *)application{
	DDLogInfo(@"Terminating application now");
	//[locationManager startMonitoringSignificantLocationChanges];
}

-(void)configureApplicationLogging{
	[DDLog addLogger:[DDASLLogger sharedInstance]];
	[DDLog addLogger:[DDTTYLogger sharedInstance]];
	DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
	fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling
	fileLogger.logFileManager.maximumNumberOfLogFiles = 14;
}

-(BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	/*if([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]){
		// We were called from background by locationManager, probably because of significant location Update
		// Send local notification to user asking him whether to record data
		if([UIApplication sharedApplication].applicationState == UIApplicationStateBackground){
			// Just and extra check to ensure we are in the background
			// [self localNotificationToUser:YES];
		}
	}
	else{
		// User confirmed the notification and wishes we record data. Application is now in foreground so lets start recording data
		UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
		if(localNotif){
			DDLogInfo(@"Received the localNotification");
			//app.applicationIconBadgeNumber = localNotif.applicationIconBadgeNumber - 1;
			[app cancelAllLocalNotifications];
			[locationManager startUpdatingLocation];
		}		
	}*/
	// Lets add logging here
	[self configureApplicationLogging];
	return YES;
}
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

/*
- (IBAction)hideApplication {
	[self dismissModalViewControllerAnimated:YES];
}
*/

-(void)updateApplicationStatusLabel{
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	if([userDefaults boolForKey:PREF_LOGGING_ENABLED]){
		applicationStatusLabel.text = [userDefaults boolForKey:OPERATE_ON_BATTERY] ? 
							@"Currently set to record on Battery" : @"Currently set to record while charging only";
	}
	else{
		applicationStatusLabel.text = @"Not recording data";
	}
}

- (void)dealloc {
	[logFilePath release];
	[locationManager release];
	[bkgndImage release];
	[startStopLogging release];
	[applicationStatusLabel release];
    [super dealloc];
}

@end
